package com.tanhua.dubbo.api;

import com.tanhua.manage.domain.mongo.FollowUser;
import com.tanhua.manage.domain.mongo.Video;
import com.tanhua.manage.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;


@Service
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 发布小视频
     *
     * @param video
     */
    @Override
    public void add(Video video) {

        video.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(video);
    }
    /**
     * 小视频分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult findPage(Long page, Long pageSize) {
        Query query = new Query();
        long total = mongoTemplate.count(query,Video.class);
        List<Video> videos = new ArrayList<>();
        if (total>0){
            query.skip((page-1)*pageSize).limit(pageSize.intValue());
            query.with(Sort.by(Sort.Order.desc("created")));
            videos = mongoTemplate.find(query, Video.class);
        }
        return PageResult.pageResult(page,pageSize,videos,total);
    }

    @Override
    public void followUser(FollowUser followUser) {
        followUser.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(FollowUser.class);
    }

    @Override
    public void unfollowUser(FollowUser followUser) {
        Query query = new Query(Criteria.where("userId").is(followUser.getUserId()).and("followUserId").is(followUser.getFollowUserId()));
        mongoTemplate.remove(query,FollowUser.class);
        //mongoTemplate.remove(followUser);
    }
}
